import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, DatePicker, Select, Space } from 'antd';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';

const { RangePicker } = DatePicker;

// 获取操作日志列表
const fetchLogs = async (params) => {
  return request('/api/v1/log', {
    method: 'GET',
    params,
  });
};

const LogList = () => {
  const [logs, setLogs] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  const [searchParams, setSearchParams] = useState({});

  // 获取日志列表
  const fetchLogList = async () => {
    try {
      setLoading(true);
      const res = await fetchLogs({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      });
      if (res.success) {
        setLogs(res.data.list || []);
        setPagination({
          ...pagination,
          total: res.data.total,
        });
      } else {
        console.error('获取日志列表失败:', res.message);
      }
    } catch (error) {
      console.error('获取日志列表出错:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchLogList();
  }, [pagination.current, pagination.pageSize, searchParams]);

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '操作用户',
      dataIndex: 'username',
      key: 'username',
      width: 120,
    },
    {
      title: '操作类型',
      dataIndex: 'method',
      key: 'method',
      width: 120,
      render: (text) => {
        const actionMap = {
          'POST': '创建',
          'PUT': '更新',
          'DELETE': '删除',
          'GET': '查询',
        };
        return actionMap[text] || text;
      },
    },
    {
      title: '操作模块',
      dataIndex: 'path',
      key: 'path',
      width: 120,
    },
    {
      title: '操作内容',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: 'IP地址',
      dataIndex: 'ip',
      key: 'ip',
      width: 130,
    },
    {
      title: '操作时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      sorter: true,
      render: (text) => moment(text*1000).format('YYYY-MM-DD HH:mm:ss'),
    },
  ];

  // 处理搜索
  const handleSearch = (values) => {
    const params = {};
    if (values.username) {
      params.username = values.username;
    }
    if (values.action) {
      params.action = values.action;
    }
    if (values.module) {
      params.module = values.module;
    }
    if (values.dateRange && values.dateRange.length === 2) {
      params.startTime = values.dateRange[0].format('YYYY-MM-DD HH:mm:ss');
      params.endTime = values.dateRange[1].format('YYYY-MM-DD HH:mm:ss');
    }

    setSearchParams(params);
    setPagination({
      ...pagination,
      current: 1, // 重置到第一页
    });
  };

  // 重置搜索
  const handleReset = () => {
    form.resetFields();
    setSearchParams({});
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 处理表格变化
  const handleTableChange = (pagination, filters, sorter) => {
    const params = { ...searchParams };

    // 处理排序
    if (sorter.field) {
      params.sortField = sorter.field;
      params.sortOrder = sorter.order === 'ascend' ? 'asc' : 'desc';
    }

    setPagination(pagination);
    setSearchParams(params);
  };

  return (
    <PageContainer>
      <Card>
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 24 }}
        >
          <Form.Item name="username" label="操作用户">
            <Input placeholder="请输入用户名" allowClear />
          </Form.Item>
          <Form.Item name="action" label="操作类型">
            <Select
              placeholder="请选择操作类型"
              style={{ width: 150 }}
              allowClear
            >
              <Select.Option value="POST">创建</Select.Option>
              <Select.Option value="PUT">更新</Select.Option>
              <Select.Option value="DELETE">删除</Select.Option>
              <Select.Option value="GET">查询</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="module" label="操作模块">
            <Input style={{ width: 150 }} placeholder="请输入操作模块" allowClear />
          </Form.Item>
          <Form.Item name="dateRange" label="操作时间">
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              placeholder={['开始时间', '结束时间']}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <Table
          columns={columns}
          dataSource={logs}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 1100 }}
        />
      </Card>
    </PageContainer>
  );
};

export default LogList;